<script lang="ts" setup>
import { ElMessage, dayjs } from 'element-plus'
import qs from 'qs'
import { GetData, GetOptionData, PostUpdateData } from '@/api/modules/weibanuser.ts'

const inquireFrom = reactive({
  UserId: '',
  UserPhone: '',
  unionid: '',
  ExternalUserId: '',
  Name: '',
  StaffName: '',
  Tags: [],
})
const dataList: any = ref([])
// 加载
const loading = ref(false)
const total = ref(0) // 总数据数
let PageSize = 20 // 每页条数

const addWayType: any = {
  0: '未知来源',
  1: '扫描二维码',
  2: '搜索手机号',
  3: '名片分享',
  4: '群聊',
  5: '手机通讯录',
  6: '微信联系人',
  8: '安装第三方应用时自动添加的客服人员',
  9: '搜索邮箱',
  10: '视频号添加',
  11: '通过日程参与人添加',
  12: '通过会议参与人添加',
  13: '添加微信好友对应的企业微信',
  14: '通过智慧硬件专属客服添加',
  15: '通过上门服务客服添加',
  16: '通过获客链接添加',
  17: '通过定制开发添加',
  18: '通过需求回复添加',
  21: '通过第三方收钱客服添加',
  22: '通过可能的商务伙伴添加',
  24: '通过接受微信账号收到的好友申请添加',
  201: '内部成员分享',
  202: '管理员/负责人分配',
}

// 获取数据
function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  loading.value = true
  const params = {
    PageIndex,
    PageSize,
    ...(inquireFrom.UserId && { UserId: inquireFrom.UserId }),
    ...(inquireFrom.UserPhone && { UserPhone: inquireFrom.UserPhone }),
    ...(inquireFrom.unionid && { UnionId: inquireFrom.unionid }),
    ...(inquireFrom.ExternalUserId && { ExternalUserId: inquireFrom.ExternalUserId }),
    ...(inquireFrom.Name && { Name: inquireFrom.Name }),
    ...(inquireFrom.StaffName && { StaffName: inquireFrom.StaffName }),
    ...(inquireFrom.Tags && { Tags: inquireFrom.Tags }),
  }
  const parameter = qs.stringify(params)
  GetData(parameter).then((res: any) => {
    if (res.succeeded) {
      dataList.value = res.data.items
      total.value = res.data.total
      loading.value = false
    }
    else {
      ElMessage.error(`查询失败。${res.errors}`)
      loading.value = false
    }
  })
}

// 查询
function Inquire() {
  GetDataList(1, PageSize)
}

// 查看详情
const viewDetailsDialog = ref(false)
const innerVisible = ref(false)
const EveryDetails = ref<any>({})
const EveryTags = ref<any>([])
const detailCollapse = ref(['1', '2', '3'])
function ViewDetails(row: any) {
  EveryDetails.value = { ...row }
  viewDetailsDialog.value = true
}
function ViewTags(row: any) {
  EveryTags.value = row.tags
  innerVisible.value = true
}

// 标签筛选
const activeNames = ref([0])
const tagDialog = ref(false)
const tagOptionList = ref<any>([])
function Open() {
  if (inquireFrom.Tags.length > 0) {
    tagOptionList.value.forEach((item: any) => {
      item.name.forEach((nameItem: any) => {
        nameItem.value = false
      })
    })

    // 如果有值则设为true
    tagOptionList.value.forEach((item: any) => {
      item.name.forEach((nameItem: any) => {
        inquireFrom.Tags.forEach((tagItem: any) => {
          if (tagItem === nameItem.name) {
            nameItem.value = true
          }
        })
      })
    })
  }
  tagDialog.value = true
}

function OnChange(index: any, indexs: any) {
  tagOptionList.value[index].name[indexs].value = !tagOptionList.value[index].name[indexs].value
}
// 清空所有标签
function ClearTag() {
  tagOptionList.value.forEach((item: any) => {
    item.name.forEach((nameItem: any) => {
      nameItem.value = false
    })
  })
}
// 提交标签并筛选数据
function TagScreen() {
  tagDialog.value = false
  inquireFrom.Tags = tagOptionList.value.flatMap((group: any) => group.name) // 将所有组的name数组合并成一个数组
    .filter((item: any) => item.value === true) // 筛选出value为true的对象
    .map((item: any) => item.name) // 提取name属性
}

// 更新数据
function UpdateData(row: any) {
  PostUpdateData(row.wbUId).then((res: any) => {
    if (res.succeeded) {
      ElMessage.success('更新成功')
      GetDataList()
    }
    else {
      ElMessage.error(`更新失败。${res.errors}`)
    }
  })
}

// 页码
function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
}

onMounted(() => {
  GetDataList()
  GetOptionData().then((res: any) => {
    if (res.succeeded) {
      tagOptionList.value = res.data
      tagOptionList.value.forEach((item: any) => {
        if (Array.isArray(item.name)) {
          // 将name数组转换为对象数组
          item.name = item.name.map((nameItem: any) => ({
            name: nameItem,
            value: false,
          }))
        }
      })
    }
    else {
      ElMessage.error(`查询失败。${res.errors}`)
    }
  })
})
</script>

<template>
  <PageMain>
    <SearchBar :show-toggle="false">
      <div class="header">
        <el-form>
          <div class="from">
            <!-- <el-form-item label="微信开放平台的唯一身份标识" style="grid-column: 1 / 3;">
              <el-input v-model="inquireFrom.Unionid" placeholder="请输入微信开放平台的唯一身份标识" clearable />
            </el-form-item> -->
            <el-form-item label="用户ID">
              <el-input v-model="inquireFrom.UserId" placeholder="请输入用户ID" clearable @keyup.enter="Inquire" />
            </el-form-item>
            <el-form-item label="用户手机号">
              <el-input v-model="inquireFrom.UserPhone" placeholder="请输入用户手机号" clearable @keyup.enter="Inquire" />
            </el-form-item>
            <el-form-item label="unionid">
              <el-input v-model="inquireFrom.unionid" placeholder="请输入unionid" clearable @keyup.enter="Inquire" />
            </el-form-item>
            <el-form-item label="外部联系人客户ID">
              <el-input v-model="inquireFrom.ExternalUserId" placeholder="请输入外部联系人客户ID" clearable @keyup.enter="Inquire" />
            </el-form-item>
            <el-form-item label="外部联系人昵称">
              <el-input v-model="inquireFrom.Name" placeholder="请输入外部联系人昵称" clearable @keyup.enter="Inquire" />
            </el-form-item>
            <el-form-item label="员工昵称">
              <el-input v-model="inquireFrom.StaffName" placeholder="请输入员工昵称" clearable @keyup.enter="Inquire" />
            </el-form-item>
            <el-form-item label="标签">
              <el-select
                v-model="inquireFrom.Tags"
                multiple
                placeholder="请筛选标签"
              >
                <el-option
                  v-for="(item, index) in inquireFrom.Tags"
                  :key="index"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </div>
        </el-form>
        <div class="text-right">
          <el-button @click="Inquire">
            查询
          </el-button>
        </div>
      </div>
    </SearchBar>
    <ElDivider border-style="dashed" />
    <div class="mb-5 text-right">
      <el-button @click="Open">
        标签筛选
      </el-button>
    </div>
    <el-table v-loading="loading" :data="dataList" stripe style="width: 100%;" border>
      <el-table-column align="center" prop="wbUId" label="ID" width="100" />
      <el-table-column align="center" prop="subscriber.userId" label="用户ID" width="100" />
      <el-table-column align="center" prop="subscriber" label="用户信息" width="200">
        <template #default="scope">
          <div v-if="scope.row.subscriber?.userId === 0">
            未授权
          </div>
          <div v-else class="user-name">
            <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.subscriber?.userAvatar" />
            <div>
              <p style="margin: 0;">
                {{ scope.row.subscriber?.userNickName }}
              </p>
              <span>
                {{ scope.row.subscriber?.userPhone }}
              </span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column header-align="center" prop="unionid" label="unionid" width="300" />
      <el-table-column header-align="center" prop="subscriber.scOpenId" label="用户OpenId" width="300" />
      <el-table-column align="center" prop="externalUserId" label="外部联系人客户ID" width="340" />
      <el-table-column align="center" prop="productName" label="外部联系人头像" width="100">
        <template #default="scope">
          <el-avatar shape="square" :size="60" :src="scope.row.avatar" />
        </template>
      </el-table-column>
      <el-table-column align="center" prop="name" label="外部联系人昵称" width="150" />
      <el-table-column align="center" prop="type" label="联系人类型" width="150">
        <template #default="scope">
          {{ scope.row.type === 1 ? '微信用户' : scope.row.type === 2 ? '企业微信用户' : '未知' }}
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" prop="organizationId" label="关联企业ID" width="150" /> -->
      <!-- <el-table-column align="center" prop="tycId" label="企业天眼查ID" width="150" /> -->
      <!-- <el-table-column header-align="center" prop="desp" label="描述" width="300" /> -->
      <el-table-column header-align="center" prop="type" label="标签" width="350">
        <template #default="scope">
          <el-scrollbar height="70px">
            <span v-for="(item, index) in scope.row.followStuffs" :key="index">
              <el-tag v-for="(items, indexs) in item.tags" :key="indexs" style="margin-right: 5px;margin-bottom: 5px;">
                {{ items.name }}
              </el-tag>
            </span>
          </el-scrollbar>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="addTime" label="添加时间" width="200" />
      <el-table-column align="center" prop="updateTime" label="更新时间" width="200" />
      <el-table-column align="center" prop="enable" label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" @click="ViewDetails(scope.row)">
            详情
          </el-button>
          <el-button type="success" @click="UpdateData(scope.row)">
            更新
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="height: 10px;" />
    <el-pagination
      :default-page-size="20"
      :page-sizes="[5, 10, 20, 50, 100]"
      layout="total, sizes, ->, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 标签筛选 -->
    <el-dialog v-model="tagDialog" title="标签筛选" width="500" :destroy-on-close="true">
      <el-collapse v-model="activeNames">
        <el-collapse-item v-for="(item, index) in tagOptionList" :key="index" :title="item.group" :name="index">
          <div class="tag-box">
            <el-check-tag v-for="(items, indexs) in item.name" :key="indexs" :checked="items.value" type="primary" @change="OnChange(index, indexs)">
              {{ items.name }}
            </el-check-tag>
          </div>
        </el-collapse-item>
      </el-collapse>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="ClearTag">
            清空
          </el-button>
          <el-button type="primary" @click="TagScreen">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情 -->
    <el-dialog v-model="viewDetailsDialog" title="详细信息" width="1600">
      <el-collapse v-model="detailCollapse">
        <el-collapse-item title="用户信息" name="1">
          <el-descriptions border :column="4">
            <el-descriptions-item :rowspan="2" :width="140" label="用户头像" align="center">
              <el-avatar :size="60" shape="square" :src="EveryDetails.subscriber?.userAvatar" />
            </el-descriptions-item>
            <el-descriptions-item label="用户ID">
              {{ EveryDetails.subscriber.userId }}
            </el-descriptions-item>
            <el-descriptions-item label="用户昵称">
              {{ EveryDetails.subscriber.userNickName }}
            </el-descriptions-item>
            <el-descriptions-item label="授权手机号">
              {{ EveryDetails.subscriber.userPhone }}
            </el-descriptions-item>
            <el-descriptions-item label="OpenId">
              {{ EveryDetails.subscriber.scOpenId }}
            </el-descriptions-item>
          </el-descriptions>
        </el-collapse-item>
        <el-collapse-item title="外部联系人" name="2">
          <el-descriptions border :column="4">
            <el-descriptions-item :rowspan="2" :width="140" label="外部联系人头像" align="center">
              <el-avatar :size="60" shape="square" :src="EveryDetails.avatar" />
            </el-descriptions-item>
            <el-descriptions-item label="联系人昵称">
              {{ EveryDetails.name }}
            </el-descriptions-item>
            <el-descriptions-item label="联系人性别">
              {{ EveryDetails.gender === 2 ? '女' : EveryDetails.gender === 1 ? '男' : '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="联系人类型">
              {{ EveryDetails.type === 1 ? '微信用户' : EveryDetails.type === 2 ? '企业微信用户' : '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="OpenId">
              {{ EveryDetails.subscriber.scOpenId }}
            </el-descriptions-item>
            <el-descriptions-item label="联系人客户ID">
              {{ EveryDetails.externalUserId }}
            </el-descriptions-item>
            <el-descriptions-item v-if="EveryDetails.type === 2" label="联系人职位">
              {{ EveryDetails.position }}
            </el-descriptions-item>
            <el-descriptions-item v-if="EveryDetails.type === 2" label="企业主体名称">
              {{ EveryDetails.corpFullName }}
            </el-descriptions-item>
            <el-descriptions-item v-if="EveryDetails.type === 2" label="企业简称">
              {{ EveryDetails.corpName }}
            </el-descriptions-item>
            <el-descriptions-item label="数据创建时间">
              {{ dayjs.unix(EveryDetails.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
            </el-descriptions-item>
            <el-descriptions-item label="数据更新时间">
              {{ dayjs.unix(EveryDetails.updatedAt).format('YYYY-MM-DD HH:mm:ss') }}
            </el-descriptions-item>
            <!-- <el-descriptions-item label="自定义展示信息">
              {{ EveryDetails.externalProfile }}
            </el-descriptions-item> -->
          </el-descriptions>
        </el-collapse-item>
        <el-collapse-item title="关联企业" name="3">
          <el-descriptions border :column="4">
            <el-descriptions-item label="关联企业ID">
              {{ EveryDetails.organizationId }}
            </el-descriptions-item>
            <el-descriptions-item label="天眼查ID">
              {{ EveryDetails.tycId }}
            </el-descriptions-item>
            <el-descriptions-item label="unionid">
              {{ EveryDetails.unionid }}
            </el-descriptions-item>
            <el-descriptions-item label="关联企业时间">
              {{ EveryDetails.organizationCorrelationTime }}
            </el-descriptions-item>
            <el-descriptions-item label="用户评分">
              {{ EveryDetails.score }}
            </el-descriptions-item>
          </el-descriptions>
        </el-collapse-item>
      </el-collapse>
      <el-table :data="EveryDetails.followStuffs" stripe style="width: 100%;" border height="240">
        <el-table-column align="center" prop="wbUFsId" label="wbUFsId" width="100" />
        <el-table-column align="center" prop="id" label="ID" width="340" />
        <el-table-column align="center" prop="staffId" label="员工ID" width="320" />
        <el-table-column align="center" prop="staffName" label="员工昵称" width="150" />
        <el-table-column align="center" prop="staffAvatar" label="员工头像" width="100">
          <template #default="scope">
            <el-avatar shape="square" :size="60" :src="scope.row.staffAvatar" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="addWay" label="该成员添加此客户的来源" width="200">
          <template #default="scope">
            <span>
              {{ addWayType[scope.row.addWay as number] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="followTime" label="好友关系创建时间" width="200">
          <template #default="scope">
            <span>
              {{ dayjs.unix(scope.row.followTime).format('YYYY-MM-DD HH:mm:ss') }}
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="state" label="渠道ID" width="150" />
        <el-table-column align="center" prop="stateType" label="渠道类型" width="150" />
        <el-table-column align="center" prop="stateName" label="渠道名称" width="200" />
        <el-table-column header-align="center" prop="stateText" label="渠道说明" width="300" />
        <el-table-column align="center" prop="remark" label="备注名" width="150" />
        <el-table-column header-align="center" prop="description" label="备注信息" width="250" />
        <el-table-column align="center" prop="remarkMobiles" label="对客户备注手机号码" width="160" />
        <el-table-column align="center" prop="deleted" label="员工是否删除客户" width="150">
          <template #default="scope">
            {{ scope.row.deleted ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column header-align="center" prop="desp" label="描述" width="300" />
        <el-table-column align="center" prop="addTime" label="添加时间" width="200" />
        <el-table-column align="center" prop="updateTime" label="更新时间" width="200" />
        <el-table-column align="center" prop="enable" label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" @click="ViewTags(scope.row)">
              企业标签信息
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-model="innerVisible" width="1200" title="标签详情" append-to-body>
        <el-table :data="EveryTags" stripe style="width: 100%;" border height="240">
          <el-table-column align="center" prop="wbUFsTId" label="wbUFsTId" width="100" />
          <el-table-column align="center" prop="staffId" label="员工ID" width="340" />
          <el-table-column align="center" prop="staffName" label="员工昵称" width="150" />
          <el-table-column align="center" prop="id" label="外部联系人客户ID" width="340" />
          <el-table-column align="center" prop="group" label="标签组名称" width="150" />
          <el-table-column align="center" prop="name" label="标签名称" width="150" />
          <el-table-column align="center" prop="addTime" label="添加时间" width="200" />
        </el-table>
      </el-dialog>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="viewDetailsDialog = false">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </PageMain>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;
  grid-gap: 20px;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;
  margin-right: 25px;

  div {
    text-align: left;
  }
}

.tag-box {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;

  span {
    margin-right: 10px;
    margin-bottom: 5px;
    font-size: 13px;
    font-weight: 400;
  }
}
</style>
